package appUtils;

import android.app.Activity;
import android.content.Context;
import android.os.Process;

import java.util.ArrayList;
import java.util.List;

import apiUtils.BaseAPIS;
import constant.AppConstants;

/**
 * Created by sth0409 on 2017/03/28-14:17.
 */

public class AppUtil {
    private static final List<Activity> activityList = new ArrayList<>();
    private static Context mContext;

    private AppUtil() {
    }

    public synchronized static AppUtil getInstance() {
        return holder.appUtil;
    }

    public void init(Context context){
        mContext = context;
    }

    public void pushAC(Activity activity) {
        activityList.add(activity);
        if (!activity.getClass().getSimpleName().equals("WelcomeActivity")) {
            SharedPreferencesManager.getInstance(activity).saveString(SharedPreferencesManager.TOP_ACTIVITY, activity.getClass().getSimpleName());
        }
    }

    public void removeAC(Activity activity) {
        activityList.remove(activity);
    }

    public void finishAc(Class<?> clazz) {
        if (clazz != null) {
            if (containAc(clazz)) {
                for (Activity ac : activityList) {
                    if (ac.getClass().equals(clazz)) {
                        ac.finish();
                    }
                }
            }
        }
    }

    private boolean containAc(Class<?> clazz) {
        for (Activity activity : activityList) {
            if (activity.equals(clazz)) {
                return true;
            }
        }
        return false;
    }

    public void finishAllAC() {
        for (Activity activity : activityList) {
            activity.finish();
        }
    }

    public Class getTopAC() {
        return activityList.isEmpty() ? null : activityList.get(activityList.size() - 1).getClass();
    }

    public void exit() {
        BaseAPIS.getInstance().destroy();
        getInstance().finishAllAC();
        Process.killProcess(Process.myPid());
        AppConstants.isAppFinish = true;
        AppConstants.timeRunning = false;
    }

    public Context getContext() {
        return mContext;
    }

    private static class holder {
        private static final AppUtil appUtil = new AppUtil();
    }
}
